package com.iogogogo.tenant.config;

import com.google.common.collect.Maps;
import com.iogogogo.tenant.config.dao.DataSourceConfigDao;
import com.iogogogo.tenant.domain.pojo.TenantDataSourceConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * Created by tao.zeng on 2021/8/8.
 */
@Component
public class TenantDataSource {

    private final Map<String, DataSource> dataSourceMap = Maps.newHashMap();

    private final DataSourceConfigDao dataSourceConfigDao;

    public TenantDataSource(DataSourceConfigDao dataSourceConfigDao) {
        this.dataSourceConfigDao = dataSourceConfigDao;
    }

    public Map<String, DataSource> getAll() {
        List<TenantDataSourceConfig> list = dataSourceConfigDao.getAll();
        Map<String, DataSource> result = Maps.newHashMap();
        for (TenantDataSourceConfig config : list) {
            DataSource dataSource = getDataSource(config);
            result.put(config.getName(), dataSource);
        }
        return result;
    }

    public DataSource getDataSource(TenantDataSourceConfig config) {
        if (dataSourceMap.containsKey(config.getName())) {
            return dataSourceMap.get(config.getName());
        }
        DataSource dataSource = createDataSource(config);
        dataSourceMap.put(config.getName(), dataSource);
        return dataSource;
    }

    private DataSource createDataSource(TenantDataSourceConfig config) {
        HikariDataSource dataSource = (HikariDataSource) DataSourceBuilder.create().build();
        dataSource.setJdbcUrl(config.getUrl());
        dataSource.setDriverClassName(config.getDriverClassName());
        dataSource.setUsername(config.getUsername());
        dataSource.setPassword(config.getPassword());
        return dataSource;
    }
}
